package com.zadetk.helpyou.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.squareup.picasso.Picasso;
import com.zadetk.helpyou.R;
import com.zadetk.helpyou.adapter.MyAdapter;
import com.zadetk.helpyou.base.AbsActivity;
import com.zadetk.helpyou.bean.HotservicecatBean;
import com.zadetk.helpyou.bean.ServicecatBean;
import com.zadetk.helpyou.bean.SkilllistBean;
import com.zadetk.helpyou.net.BaseObserver;
import com.zadetk.helpyou.net.BaseResponse;
import com.zadetk.helpyou.net.NetTool;
import com.zadetk.helpyou.other.UserInfoManger;
import com.zadetk.helpyou.utils.LogUtil;
import com.zadetk.helpyou.view.NoScrollView;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 4-3-1搜索页面
 */
public class SearchItemActivity extends AbsActivity implements View.OnClickListener{
    private static final String TAG = SearchItemActivity.class.getName();
    private EditText etSearch;
    private TextView tvCancel;
    private NoScrollView gvTag;
    private LinearLayout llHotTag;
    private TagFlowLayout flTag;
    private LinearLayout llList;
    private RecyclerView recycleview;
    private ArrayList<String> list = new ArrayList<>();
    private List<ServicecatBean> data = new LinkedList<>();
    private List<HotservicecatBean> data1 = new LinkedList<>();
    private SearchAdapter searchAdapter;
    private ImageView ivBack;
    private List<String> tagList = new LinkedList<>();
    private ImageView iv;
    private TextView tv;
    private String title;

    /**
     * Find the Views in the layout<br />
     * <br />
     * Auto-created on 2018-05-14 13:40:54 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    private void initViews() {
        etSearch = findViewById(R.id.et_search);
        tvCancel = findViewById(R.id.tv_cancel);
        gvTag = findViewById(R.id.gv_tag);
        llHotTag = findViewById(R.id.ll_hot_tag);
        flTag = findViewById(R.id.fl_tag);
        llList = findViewById(R.id.ll_list);
        recycleview = findViewById(R.id.recycleview);
        ivBack = findViewById(R.id.iv_back);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleview.setLayoutManager(linearLayoutManager);
        setTopTitle("发布服务");
        llList.setVisibility(View.GONE);
        llHotTag.setVisibility(View.GONE);
    }

    @Override
    public int setView() {
        return R.layout.activity_search_item;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        initViews();
        getHotList();
        initLogic();
        getServiceList();

    }

    private void initLogic() {
        gvTag.setAdapter(new MyServiceAdapter(this){
        });
        gvTag.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                intent.setClass(SearchItemActivity.this, PublishServiceSubActivity.class);
                intent.putExtra("panrentid",data.get(position).getCatid());
//                Log.i(TAG, "initBasic: =========" +data.get(position).getCatid());
                startActivity(intent);
            }
        });
        // 搜索框
        etSearch.clearFocus();
        etSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    llHotTag.setVisibility(View.VISIBLE);
                    llList.setVisibility(View.GONE);
                    gvTag.setVisibility(View.GONE);
                    tvCancel.setVisibility(View.VISIBLE);
                } else {
                    tvCancel.setVisibility(View.GONE);
                    llHotTag.setVisibility(View.GONE);
                    llList.setVisibility(View.GONE);
                    gvTag.setVisibility(View.VISIBLE);
                }
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(editable.toString())) {
                    if (etSearch.hasFocus()) {
                        llHotTag.setVisibility(View.VISIBLE);
                        llList.setVisibility(View.GONE);
                        gvTag.setVisibility(View.GONE);
                    } else {
                        llHotTag.setVisibility(View.GONE);
                        llList.setVisibility(View.GONE);
                        gvTag.setVisibility(View.VISIBLE);
                    }
                } else {
                    llHotTag.setVisibility(View.GONE);
                    llList.setVisibility(View.VISIBLE);
                    gvTag.setVisibility(View.GONE);
                }
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tvCancel.setVisibility(View.GONE);
                etSearch.setText("");
                InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(SearchItemActivity.this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
                etSearch.clearFocus();
            }
        });
        // item2 房屋维修
        searchAdapter = new SearchAdapter(R.layout.search_item2, data);
        searchAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(SearchItemActivity.this, PublishServiceActivity.class));
            }
        });
        recycleview.setAdapter(searchAdapter);
        Log.i(TAG, "233: 0======="+tagList);
    }
    // 获取热门类别数据
    private void getHotList() {
        Map<String, Object> param = NetTool.newParams();
        param.put("uid", UserInfoManger.userInfo.getUid());
        param.put("token", UserInfoManger.userInfo.getUserToken());
        NetTool.getApi().getHotservicecat(param)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<List<HotservicecatBean>>>() {
                    @Override
                    public void onData(BaseResponse<List<HotservicecatBean>> value) {
                        if (value.getCode() == 0) {
                            data1.clear();
                            List<HotservicecatBean> user = value.getData();
                            data1.addAll(user);
                            for (HotservicecatBean bean : user) {
                                LogUtil.e("1========="+bean.toString());
                            }
                            for (int i = 0;i<data1.size();i++){
                                title = data1.get(i).getCatname();
//                                Log.i(TAG, "initLogic: ==========="+data1.get(i).getCatname());
                                tagList.add(title);
                                Log.i(TAG, "233: 2==========="+tagList);
                            }
                            Log.i(TAG, "233 3======="+title);
                            LogUtil.e(user + " 4============ " + value.getMessage());
                        } else {
                            LogUtil.e(value.error_code + " error code");
                        }
                        Log.i(TAG, "233 5======="+tagList);
                        final TagAdapter tagAdapter = new TagAdapter<String>(tagList) {
                            @Override
                            public View getView(FlowLayout parent, int position, String s) {
                                TextView tv = (TextView) getLayoutInflater().inflate(R.layout.tag_text, null);
                                tv.setText(s);
                                return tv;
                            }
                        };
                        flTag.setAdapter(tagAdapter);
                        flTag.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
                            @Override
                            public boolean onTagClick(View view, int position, FlowLayout parent) {
                                startActivity(new Intent(SearchItemActivity.this, PublishServiceActivity.class));
                                return false;
                            }
                        });
                    }
                });
    }
    // 获取一级分类数据
    private void getServiceList() {
        Map<String, Object> param = NetTool.newParams();
        param.put("uid", UserInfoManger.userInfo.getUid());
        param.put("token", UserInfoManger.userInfo.getUserToken());
        NetTool.getApi().getServicecat(param)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<List<ServicecatBean>>>() {
                    @Override
                    public void onData(BaseResponse<List<ServicecatBean>> value) {
                        if (value.getCode() == 0) {
                            data.clear();
                            List<ServicecatBean> user = value.getData();
                            data.addAll(user);
                            for (ServicecatBean bean : user) {
                                LogUtil.e("=="+bean.toString());
                                list.add("");
                                Log.i(TAG, "onData: ==="+list.size());
                            }
//                            searchAdapter.notifyDataSetChanged();
//                            myServiceAdapter.notifyDataSetChanged();

                            LogUtil.e(user + " == " + value.getMessage());
                        } else {
                            LogUtil.e(value.error_code + "== error code");
                        }
                    }

                });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
//                InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
//                inputMethodManager.hideSoftInputFromWindow(SearchItemActivity.this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
                finish();
                break;
        }
    }

    //搜索Adapter
    private class SearchAdapter extends BaseQuickAdapter<ServicecatBean, BaseViewHolder> {

        public SearchAdapter(int layoutResId, @Nullable List<ServicecatBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, ServicecatBean item) {
        }
    }

    // 分类Adapter
    private class MyServiceAdapter extends BaseAdapter {
        Context context;
        public MyServiceAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            //通过布局填充器LayoutInflater填充网格单元格内的布局
            View v = LayoutInflater.from(context).inflate(R.layout.search_item, null);
            //使用findViewById分别找到单元格内布局的图片以及文字
            iv = (ImageView) v.findViewById(R.id.iv_search);
            tv = (TextView) v.findViewById(R.id.tv_search);
            //引用数组内元素设置布局内图片以及文字的内容
            String url = data.get(position).getCatico();
//            Picasso.get().
//                    load(url)
//                    .placeholder(R.drawable.list_ico2)
//                    .error(R.drawable.list_ico3)
//                    .into(iv);
//
            // TODO 加载图片过程中默认图以及加载失败的图片
            Glide.with(context)
                    .load(url)
                    .placeholder(R.drawable.aliwx_head_default)//图片加载出来前，显示的图片
                    .error(R.drawable.aliwx_default_gallery_image)//图片加载失败后，显示的图片
                    .into(iv);
//            Picasso.get().load(data.get(position).getCatico()).into(iv);
            tv.setText(data.get(position).getCatname());
            //返回值一定为单元格整体布局v
            return v;
        }
    }

}
